import{Config} from "./config.js";

class Token{
  constructor() {
    this.token_url = Config.baseRequestUrl+'/token/';
    this.check_token_url = Config.baseRequestUrl + '/token/check';
  }

  // 验证token
  checkToken(){
    var token = wx.getStorageSync('token');
    if (!token) {
      this.getToken();
    }
    else {
      this._checkRequestToken(token);
    } 
  }

  // 获取token
  getToken(callback){
    var that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.request({
            url: that.token_url+ res.code,
            success: function (res) {
              var data = res.data.data
              wx.setStorageSync('token', data.token);  //将token存入缓存中
              callback && callback(res.data.token);
            }
          })
        } else {
          wx.showLoading({
            title: '登录错误，稍后再试~',
          })
        }
      }
    })
  }

  // 验证token是否过期
  _checkRequestToken(token){
    var that=this;
    wx.request({
      url: that.check_token_url,
      method: 'POST',
      data: {
        token: token
      },
      success: function (res) {
        var code = res.statusCode.toString();
        if (code=='401') {   //过期则重新获取
          that.getToken();
        }
      }
    })
  }

}
export {Token};